<template>
  <el-upload
    class="mg-l"
    accept=""
    action="https://jsonplaceholder.typicode.com/posts/"
    :show-file-list="false"
    :auto-upload="false"
    :on-change="progress"
  >
    <slot></slot>
  </el-upload>
</template>

<script>
  import { headers } from "../../utils/request";
  import xlsx from "xlsx";
  import { computed, defineComponent,ref,toRefs,onMounted,reactive,watch,getCurrentInstance } from 'vue'
  export default defineComponent({
    props: {
      header:{
        type:Array,
        default:[]
      },
      filterVal:{
        type:Array,
        default:[]
      },
      http_api:{
        default: "VUE_APP_API"
      },
      http_url:{
        default: "/v1/ad/upload_excel"
      }
    },
    setup(props){
      const { proxy } = getCurrentInstance()
      const data = reactive({
        loading:false,
        headers: headers(),
        clipboard:null,
        upload_url:""
      })
      onMounted(()=>{
        data.upload_url = import.meta.env[props.http_api] + props.http_url;
      })
      const progress = async file => {
        let dataBinary = await readFile(file.raw)
        let workBook = await xlsx.read(dataBinary, {type: 'binary', cellDates: true})
        let workSheet = workBook.Sheets[workBook.SheetNames[0]]
        const data = xlsx.utils.sheet_to_json(workSheet)
        const tHeader = props.header
        const filterVal = props.filterVal
        let result = data.map(row=>{
          let new_row = {}
          tHeader.forEach((val,key)=>{
            new_row[filterVal[key]] = row[val]
          })
          return new_row
        })
        proxy.$emit("onChange",result)
      }
      const readFile = file => {
        return new Promise(resolve => {
          let reader = new FileReader()
          reader.readAsBinaryString(file)
          reader.onload = ev => {
            resolve(ev.target.result)
          }
        })
      }
      return{
        ...props,
        ...toRefs(data),
        progress,
      }
    }
  })

</script>
<style scoped lang='less'>

</style>
<style lang='less'>

</style>